<route lang="json5">
{
  meta: {
    auth: true,
    label: '小窗',
    layout: 'Empty',
  },
}
</route>

<template>
  <div class="p-2">
    <p>这是小窗</p>
    <a-divider />
    <a-button @click="handleSend">BroadcastChannel</a-button>
    <a-divider />

    <div class="grid grid-cols-3 w-max gap-4">
      <div
        v-for="item in 9"
        @mouseenter="handleChangeActive(item)"
        @mouseleave="handleChangeActive(0)"
        :class="{
          'bg-blue-100': active === item,
        }"
        class="h-12 w-12 bg-red-50 transition-all duration-200 cursor-pointer"
      ></div>
    </div>
  </div>
</template>

<script lang="ts" setup>
const channel = new BroadcastChannel('channel-PAKCHOI.XXXX')

const active = ref(0)

function handleChangeActive(value: number) {
  active.value = value
  channel && channel.postMessage({ command: 'change-active', value })
}

function handleSend() {
  channel.postMessage('吃了')
}

function handleMessage({ data }: any) {
  if (!data.command) {
    Message.clear()
    Message.info(JSON.stringify(data))
  } else {
    console.log(data)
    switch (data.command) {
      case 'change-active':
        active.value = data.value
        break
    }
  }
}

onBeforeMount(() => {
  window.addEventListener('message', handleMessage)
})

onUnmounted(() => {
  window.removeEventListener('message', handleMessage)
})
</script>
